from fastapi import APIRouter, HTTPException, Query, Request, BackgroundTasks, Depends, Header
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import database
import os
import re
from openai import OpenAI
import logging
import asyncio
import json
from starlette.concurrency import run_in_threadpool
from asyncio.exceptions import CancelledError
from starlette.background import BackgroundTask
import threading
import time
import weakref
import signal
import sys
import jwt
from jwt.exceptions import PyJWTError, InvalidTokenError, InvalidSignatureError
from datetime import datetime, timedelta

# JWT配置
# 从认证模块导入SECRET_KEY和ALGORITHM，确保一致性
try:
    from auth import SECRET_KEY, ALGORITHM
except ImportError:
    # 如果导入失败，使用默认值
    SECRET_KEY = "your-super-secret-key-for-music-assistant-app-2024" # 实际应用中应放在环境变量中
    ALGORITHM = "HS256"
    logging.warning("无法从auth模块导入JWT配置，使用默认值")

ACCESS_TOKEN_EXPIRE_MINUTES = 1440  # 24小时

# 创建一个可被弱引用的包装类
class StreamData:
    def __init__(self, data):
        self.data = data

# 保存活跃连接
active_streams = {}
# 设置最大连接存活时间（秒）
MAX_STREAM_LIFETIME = 60
# 强制终止持续报错的时间（秒）
MAX_ERROR_TIME = 10

# 记录错误发生的时间
error_timestamps = {}

# 监控线程
def monitor_active_streams():
    while True:
        current_time = time.time()
        
        # 检查持续报错情况
        for stream_id, timestamp in list(error_timestamps.items()):
            if current_time - timestamp > MAX_ERROR_TIME:
                logger.critical(f"检测到流 {stream_id} 持续报错超过 {MAX_ERROR_TIME} 秒，尝试强制终止")
                # 移除错误记录
                error_timestamps.pop(stream_id, None)
                # 如果在活跃流中存在，移除它
                if stream_id in active_streams:
                    try:
                        stream_data = active_streams[stream_id]
                        # 保存内容
                        if 'content' in stream_data.data and stream_data.data['content'].strip():
                            asyncio.run_coroutine_threadsafe(
                                save_stream_content(
                                    stream_data.data['conversation_id'],
                                    stream_data.data['user_id'],
                                    stream_data.data['content']
                                ),
                                asyncio.get_event_loop()
                            )
                        # 移除流
                        active_streams.pop(stream_id, None)
                    except Exception as e:
                        logger.error(f"强制终止流 {stream_id} 时出错: {e}")
        
        # 检查所有流，清理超时的流
        for stream_id, stream_data in list(active_streams.items()):
            try:
                if current_time - stream_data.data['start_time'] > MAX_STREAM_LIFETIME:
                    logger.warning(f"发现超时流: {stream_id}，强制关闭")
                    # 执行清理操作
                    try:
                        if 'content' in stream_data.data and stream_data.data['content'].strip():
                            # 保存已收集的内容
                            asyncio.run_coroutine_threadsafe(
                                save_stream_content(
                                    stream_data.data['conversation_id'], 
                                    stream_data.data['user_id'], 
                                    stream_data.data['content']
                                ),
                                asyncio.get_event_loop()
                            )
                    except Exception as e:
                        logger.error(f"清理超时流时出错: {e}")
                    
                    # 从活跃流中移除
                    active_streams.pop(stream_id, None)
            except Exception as e:
                logger.error(f"监控流时发生错误: {e}")
        
        # 每2秒检查一次
        time.sleep(2)

# 注册错误处理器
def register_socket_error_handler():
    original_exception_handler = asyncio.get_event_loop().get_exception_handler()
    
    def custom_exception_handler(loop, context):
        exception = context.get('exception')
        if exception and 'socket.send() raised exception' in str(context.get('message', '')):
            # 记录错误发生时间
            error_info = str(context.get('message', ''))
            # 尝试提取流ID从错误信息中
            stream_id = None
            try:
                # 这里根据日志格式提取，实际情况可能需要调整
                message_parts = error_info.split()
                for part in message_parts:
                    if part.startswith('stream_'):
                        stream_id = part
                        break
            except:
                pass
            
            if stream_id:
                # 记录或更新错误时间戳
                error_timestamps[stream_id] = time.time()
                logger.warning(f"注册流错误: {stream_id}, 信息: {error_info}")
        
        # 调用原始的异常处理器
        if original_exception_handler is not None:
            original_exception_handler(loop, context)
    
    asyncio.get_event_loop().set_exception_handler(custom_exception_handler)

# 在服务启动时注册错误处理器
register_socket_error_handler()

# 保存流内容的协程
async def save_stream_content(conversation_id, user_id, content):
    try:
        logger.info(f"保存流内容: 会话ID {conversation_id}, 用户ID {user_id}, 内容长度 {len(content)}")
        # 保存消息到数据库
        assistant_message_id = database.save_message(
            user_id=user_id,
            conversation_id=conversation_id,
            role="assistant",
            content=content
        )
        
        if assistant_message_id:
            # 更新用户统计信息
            database.update_user_stat(user_id, "conversation_count")
            logger.info(f"超时流内容保存成功, 消息ID: {assistant_message_id}")
    except Exception as e:
        logger.error(f"保存超时流内容时出错: {e}")

# 启动监控线程
monitor_thread = threading.Thread(target=monitor_active_streams, daemon=True)
monitor_thread.start()

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 创建API路由
router = APIRouter(tags=["chat"])

# 添加CORS中间件
def add_cors_middleware(app):
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["http://localhost:8080"],  # 允许前端域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 创建请求模型
class ChatRequest(BaseModel):
    message: str
    conversation_id: Optional[int] = None

class ChatBotResponse(BaseModel):
    success: bool
    message: str
    conversation_id: Optional[int] = None

# 初始化聊天机器人
chat_bot = None

def init_chat_bot():
    global chat_bot
    api_key = "sk-175ecab4b7a3477b909aff5725e5a6f3"
    if not api_key:
        logger.warning("未设置DeepSeek API密钥，聊天功能将不可用")
        return False
    
    try:
        chat_bot = MusicChatBot(api_key=api_key)
        logger.info("聊天机器人初始化成功")
        return True
    except Exception as e:
        logger.error(f"聊天机器人初始化失败: {str(e)}")
        return False

class MusicChatBot:
    def __init__(self, api_key=None, base_url="https://api.deepseek.com"):
        """初始化聊天机器人"""
        self.client = OpenAI(
            api_key=api_key or os.getenv("DS_API_KEY"),
            base_url=base_url
        )
        # 系统提示，定义AI角色为音乐助手
        self.system_message = {
            "role": "system", 
            "content": "你是一个专业的音乐助手，精通乐理知识、乐器演奏技巧、音乐历史和作曲家知识。请用简洁专业的语言回答用户的音乐相关问题。支持Markdown和LaTeX数学公式，可以使用这些格式来更清晰地展示音乐符号和概念。"
        }

    def get_streaming_response(self, user_input, message_history=None):
        """获取流式AI回复"""
        try:
            # 准备消息历史
            messages = [self.system_message]
            if message_history:
                messages.extend(message_history)
            messages.append({"role": "user", "content": user_input})
            
            # 创建流式请求
            stream = self.client.chat.completions.create(
                model="deepseek-chat",
                messages=messages,
                stream=True,
                temperature=0.8,
                max_tokens=1000
            )
            
            return stream
        except Exception as e:
            logger.error(f"流式AI请求失败: {str(e)}")
            raise e

# 初始化聊天机器人
init_chat_bot()

# Token验证依赖项
async def get_current_user(
    authorization: Optional[str] = Header(None),
    token: Optional[str] = Query(None),
    request: Request = None
):
    """验证用户身份，支持从Authorization头部或query参数获取token"""
    effective_token = None
    token_source = None
    
    # 首先尝试从Authorization头部获取token
    if authorization:
        token_source = "header"
        try:
            parts = authorization.split()
            if len(parts) == 2 and parts[0].lower() == "bearer":
                effective_token = parts[1]
            else:
                effective_token = authorization
        except Exception as e:
            logger.warning(f"解析Authorization头部失败: {e}")
    
    # 如果头部没有token，尝试从query参数获取
    if not effective_token and token:
        token_source = "query"
        effective_token = token
    
    # 如果仍然没有token，尝试从请求对象的查询参数中获取
    if not effective_token and request:
        try:
            query_params = dict(request.query_params)
            if 'token' in query_params:
                token_source = "request_query"
                effective_token = query_params['token']
        except Exception as e:
            logger.warning(f"从请求对象获取token失败: {e}")
    
    # 如果没有找到有效的token，返回401错误
    if not effective_token:
        logger.warning("未提供身份验证凭据")
        raise HTTPException(status_code=401, detail="未提供身份验证凭据")
    
    logger.info(f"使用{token_source}中的token进行认证")
    
    try:
        # 解码token
        payload = jwt.decode(effective_token, SECRET_KEY, algorithms=[ALGORITHM])
        
        # 从payload中获取用户ID，优先使用id字段
        user_id = None
        if "id" in payload:
            user_id = payload["id"]
        elif "sub" in payload:
            # 兼容模式：如果没有id字段但有sub字段，尝试使用sub
            # 注意：这里假设sub可能是数字字符串或用户名
            try:
                user_id = int(payload["sub"])
            except ValueError:
                # 如果sub不是数字，尝试通过用户名查找用户
                username = payload["sub"]
                user = database.get_user_by_username(username)
                if user:
                    user_id = user["id"]
                else:
                    raise HTTPException(status_code=401, detail="无效的用户名")
        
        if user_id is None:
            raise HTTPException(status_code=401, detail="无效的身份验证凭据")
        
        # 验证用户是否存在
        user = database.get_user_details(user_id)
        if not user:
            raise HTTPException(status_code=401, detail="用户不存在")
        
        logger.info(f"用户{user_id}认证成功")
        return user_id
    except (PyJWTError, InvalidTokenError, InvalidSignatureError) as e:
        logger.error(f"JWT验证失败: {str(e)}")
        raise HTTPException(status_code=401, detail="无效的身份验证令牌")

# 创建JWT令牌
def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

@router.get("/history")
async def get_chat_history(user_id: int = Depends(get_current_user)):
    """获取用户的聊天历史"""
    # 获取会话列表
    conversations = database.get_user_conversations(user_id)
    
    # 为每个会话添加消息数量
    for conv in conversations:
        # 如果数据库返回没有包含消息数量，计算消息数量
        if "message_count" not in conv:
            # 获取会话消息数量
            message_count = database.get_conversation_message_count(conv["id"])
            conv["message_count"] = message_count
    
    return {
        "success": True,
        "conversations": conversations
    }

@router.get("/messages/{conversation_id}")
async def get_conversation_messages(conversation_id: int, user_id: int = Depends(get_current_user)):
    """获取单个会话的消息"""
    # 验证会话属于该用户
    conv = database.get_conversation(conversation_id)
    if not conv or conv["user_id"] != user_id:
        raise HTTPException(status_code=404, detail="无效的会话ID")
    
    # 获取消息
    messages = database.get_conversation_messages(conversation_id)
    
    return {
        "success": True,
        "messages": messages,
        "conversation": conv
    }

@router.post("/send")
async def send_message(request: ChatRequest, user_id: int = Depends(get_current_user)):
    """发送消息并获取AI回复"""
    if not chat_bot:
        if not init_chat_bot():
            return {"success": False, "message": "聊天服务不可用"}
    
    conversation_id = request.conversation_id
    
    # 如果没有conversation_id，创建新会话
    if not conversation_id:
        conversation_id = database.create_conversation(user_id)
        if not conversation_id:
            return {"success": False, "message": "创建会话失败"}
    
    # 获取会话历史
    message_history = database.get_conversation_messages(conversation_id)
    formatted_history = [
        {"role": msg["role"], "content": msg["content"]} 
        for msg in message_history
    ]
    
    # 保存用户消息
    user_message_id = database.save_message(
        user_id=user_id,
        conversation_id=conversation_id,
        role="user",
        content=request.message
    )
    
    if not user_message_id:
        return {"success": False, "message": "保存用户消息失败"}
    
    try:
        # 获取AI回复
        stream = chat_bot.get_streaming_response(request.message, formatted_history)
        
        # 收集完整回复以保存到数据库
        full_response = ""
        for chunk in stream:
            if chunk.choices[0].delta.content:
                full_response += chunk.choices[0].delta.content
        
        # 保存AI回复
        assistant_message_id = database.save_message(
            user_id=user_id,
            conversation_id=conversation_id,
            role="assistant",
            content=full_response
        )
        
        if not assistant_message_id:
            return {"success": False, "message": "保存AI回复失败"}
        
        # 更新用户统计信息
        database.update_user_stat(user_id, "conversation_count")
        
        return {
            "success": True,
            "message": full_response,
            "conversation_id": conversation_id
        }
    except Exception as e:
        logger.error(f"获取AI回复失败: {str(e)}")
        return {"success": False, "message": f"获取AI回复失败: {str(e)}"}

@router.post("/stream/{conversation_id}")
@router.get("/stream/{conversation_id}")
async def stream_message_with_id(
    conversation_id: int,
    background_tasks: BackgroundTasks, 
    request: Request,
    message: Optional[str] = Query(None),
    token: Optional[str] = Query(None),
    user_id: Optional[int] = Depends(get_current_user)
):
    """使用会话ID的流式消息API"""
    # 如果依赖项未解析用户ID，但提供了token查询参数，尝试手动验证
    if user_id is None and token:
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            if "id" in payload:
                user_id = payload["id"]
            elif "sub" in payload:
                # 尝试通过用户名获取ID
                try:
                    username = payload["sub"]
                    user = database.get_user_by_username(username)
                    if user:
                        user_id = user["id"]
                except:
                    pass
        except Exception as e:
            logger.error(f"从查询参数token验证失败: {e}")
    
    # 如果仍然没有用户ID，返回401错误
    if user_id is None:
        return JSONResponse(
            status_code=401,
            content={"error": "未授权访问，请提供有效的认证令牌"}
        )
    
    return await stream_message_internal(background_tasks, request, user_id, message, conversation_id)

@router.post("/stream")
@router.get("/stream")
async def stream_message_new(
    background_tasks: BackgroundTasks, 
    request: Request,
    message: Optional[str] = Query(None),
    token: Optional[str] = Query(None),
    user_id: Optional[int] = Depends(get_current_user)
):
    """创建新会话的流式消息API"""
    # 如果依赖项未解析用户ID，但提供了token查询参数，尝试手动验证
    if user_id is None and token:
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            if "id" in payload:
                user_id = payload["id"]
            elif "sub" in payload:
                # 尝试通过用户名获取ID
                try:
                    username = payload["sub"]
                    user = database.get_user_by_username(username)
                    if user:
                        user_id = user["id"]
                except:
                    pass
        except Exception as e:
            logger.error(f"从查询参数token验证失败: {e}")
    
    # 如果仍然没有用户ID，返回401错误
    if user_id is None:
        return JSONResponse(
            status_code=401,
            content={"error": "未授权访问，请提供有效的认证令牌"}
        )
    
    return await stream_message_internal(background_tasks, request, user_id, message, None)

async def stream_message_internal(
    background_tasks: BackgroundTasks, 
    request: Request,
    user_id: int,
    message: Optional[str] = None,
    conversation_id: Optional[int] = None
):
    """流式发送消息并获取AI回复的内部实现"""
    stream_id = f"stream_{time.time()}_{user_id}"
    logger.info(f"新的流请求: {stream_id}, 方法: {request.method}, 会话ID: {conversation_id}, 用户ID: {user_id}")
    
    # 记录请求信息以便调试
    request_headers = dict(request.headers)
    # 隐藏敏感信息
    if 'authorization' in request_headers:
        request_headers['authorization'] = request_headers['authorization'][:15] + '...(隐藏)'
    
    try:
        query_params = dict(request.query_params)
        # 隐藏敏感信息
        if 'token' in query_params:
            query_params['token'] = query_params['token'][:15] + '...(隐藏)'
        
        logger.info(f"请求头: {request_headers}")
        logger.info(f"查询参数: {query_params}")
    except Exception as e:
        logger.error(f"记录请求信息出错: {e}")
    
    # 清理可能存在的错误记录
    if stream_id in error_timestamps:
        error_timestamps.pop(stream_id, None)
    
    if not chat_bot:
        if not init_chat_bot():
            return JSONResponse(
                status_code=503,
                content={"error": "聊天服务不可用"}
            )
    
    # 如果是POST请求，从请求体获取数据
    if request.method == "POST" and not message:
        try:
            request_data = await request.json()
            message = request_data.get("message")
        except:
            pass
    
    # 验证必要参数
    if not message:
        return JSONResponse(
            status_code=400,
            content={"error": "消息内容不能为空"}
        )
    
    # ===== 第一阶段：会话管理、用户消息保存和ID返回 =====
    
    # 检查conversation_id的有效性
    if conversation_id is not None:
        # 验证会话存在且属于该用户
        conv = database.get_conversation(conversation_id)
        if not conv or conv["user_id"] != user_id:
            logger.warning(f"无效的会话ID: {conversation_id}")
            return JSONResponse(
                status_code=404,
                content={"error": "无效的会话ID"}
            )
        logger.info(f"使用现有会话, ID: {conversation_id}")
    
    # 如果没有会话ID，立即创建新会话
    is_new_conversation = False
    if not conversation_id:
        logger.info(f"为用户 {user_id} 创建新会话")
        # 先创建会话获取ID
        conversation_id = database.create_conversation(user_id)
        if not conversation_id:
            return JSONResponse(
                status_code=500,
                content={"error": "创建会话失败"}
            )
        is_new_conversation = True
        logger.info(f"新会话创建成功，ID: {conversation_id}")
    
    # 检查现有的活跃流，如果有相同会话ID的流，关闭它
    for key, stream_data in list(active_streams.items()):
        if stream_data.data.get('conversation_id') == conversation_id:
            logger.warning(f"发现该会话的旧流: {key}，强制关闭")
            # 保存内容
            content = stream_data.data.get('content', '')
            if content.strip():
                background_tasks.add_task(
                    save_stream_content, 
                    conversation_id, 
                    user_id, 
                    content
                )
            # 从活跃流移除
            active_streams.pop(key, None)
    
    # 保存用户消息
    user_message_id = database.save_message(
        user_id=user_id,
        conversation_id=conversation_id,
        role="user",
        content=message
    )
    
    if not user_message_id:
        return JSONResponse(
            status_code=500,
            content={"error": "保存用户消息失败"}
        )
    
    # ===== 第二阶段：AI回复处理 =====
    
    # 创建一个包装流式响应的函数，使其分为两个阶段
    async def two_phase_response():
        # 阶段1：立即返回会话ID
        yield f"data: {{\"conversation_id\": {conversation_id}}}\n\n"
        
        # 阶段2：获取并发送AI回复
        # 获取会话历史
        message_history = database.get_conversation_messages(conversation_id)
        formatted_history = [
            {"role": msg["role"], "content": msg["content"]} 
            for msg in message_history
        ]
        
        # 创建流追踪变量
        full_response_content = ""
        
        try:
            # 获取流式响应
            stream = chat_bot.get_streaming_response(message, formatted_history)
            
            for chunk in stream:
                if chunk.choices[0].delta.content:
                    content = chunk.choices[0].delta.content
                    full_response_content += content
                    # 更新活跃流中的内容
                    if stream_id in active_streams:
                        active_streams[stream_id].data['content'] = full_response_content
                    
                    # 使用标准SSE格式发送数据
                    try:
                        yield f"data: {content}\n\n"
                    except Exception as e:
                        logger.warning(f"发送数据块时发生错误: {str(e)}")
                        # 在异常时保存已收集的内容
                        if full_response_content.strip():
                            await save_assistant_message(full_response_content, conversation_id, user_id, stream_id)
                        # 重新抛出异常让外层捕获
                        raise
            
            # 流正常结束，保存内容并从活跃流中移除
            if full_response_content.strip():
                await save_assistant_message(full_response_content, conversation_id, user_id, stream_id)
            else:
                # 即使没有内容也从活跃流中移除
                if stream_id in active_streams:
                    active_streams.pop(stream_id, None)
                # 清理可能存在的错误记录
                if stream_id in error_timestamps:
                    error_timestamps.pop(stream_id, None)
            
            # 发送完成信号
            yield f"data: [DONE]\n\n"
            
        except CancelledError:
            # 客户端中断连接时，保存已收集的内容
            logger.warning(f"客户端连接被取消，流ID: {stream_id}, 会话ID: {conversation_id}")
            if full_response_content.strip():
                await save_assistant_message(full_response_content, conversation_id, user_id, stream_id)
            else:
                # 即使没有内容也从活跃流中移除
                if stream_id in active_streams:
                    active_streams.pop(stream_id, None)
            # 清理可能存在的错误记录
            if stream_id in error_timestamps:
                error_timestamps.pop(stream_id, None)
            
        except Exception as e:
            logger.error(f"流式响应出错: {str(e)}, 流ID: {stream_id}")
            # 从活跃流中移除
            if stream_id in active_streams:
                active_streams.pop(stream_id, None)
            # 清理可能存在的错误记录
            if stream_id in error_timestamps:
                error_timestamps.pop(stream_id, None)
            
            # 尝试发送错误消息给客户端
            try:
                yield f"data: ⚠️ 请求失败: {str(e)}\n\n"
                yield f"data: [DONE]\n\n"
            except:
                # 如果发送失败，忽略它并确保内容被保存
                pass
                
            # 保存已经收集的内容
            if full_response_content.strip():
                await save_assistant_message(full_response_content, conversation_id, user_id, stream_id)
    
    # 定义新的保存消息函数，不再引用闭包外部的变量
    async def save_assistant_message(content, conv_id, uid, sid):
        if not content.strip():
            logger.warning(f"空回复内容，不保存，会话ID: {conv_id}, 流ID: {sid}")
            return
            
        try:
            # 从活跃流中移除
            if sid in active_streams:
                active_streams.pop(sid, None)
            # 清理可能存在的错误记录
            if sid in error_timestamps:
                error_timestamps.pop(sid, None)
            
            # 保存AI的回复内容
            logger.info(f"保存AI回复，会话ID: {conv_id}，内容长度: {len(content)}")
            assistant_message_id = database.save_message(
                user_id=uid,
                conversation_id=conv_id,
                role="assistant",
                content=content
            )
            
            if assistant_message_id:
                # 更新用户统计信息
                database.update_user_stat(uid, "conversation_count")
                logger.info(f"AI回复保存成功，ID: {assistant_message_id}")
            else:
                logger.warning(f"保存AI回复失败: {content[:100]}...")
        except Exception as e:
            logger.error(f"保存AI回复时出错: {str(e)}")
    
    # 定义关闭流函数
    def on_disconnect():
        try:
            logger.info(f"流 {stream_id} 断开连接")
            # 从活跃流中移除
            if stream_id in active_streams:
                # 获取内容和会话ID用于保存
                stream_data = active_streams[stream_id]
                content = stream_data.data.get('content', '')
                conv_id = stream_data.data.get('conversation_id')
                uid = stream_data.data.get('user_id')
                
                # 移除流
                active_streams.pop(stream_id, None)
                
                # 如果存在有效内容，保存它
                if content.strip() and conv_id and uid:
                    logger.warning(f"连接关闭，后台保存内容，会话ID: {conv_id}，内容长度: {len(content)}")
                    asyncio.create_task(save_assistant_message(content, conv_id, uid, stream_id))
            
            # 清理可能存在的错误记录
            if stream_id in error_timestamps:
                error_timestamps.pop(stream_id, None)
        except Exception as e:
            logger.error(f"流断开处理失败: {e}")
    
    # 将流添加到活跃流字典中 - 使用包装类
    stream_info = {
        'stream_id': stream_id,  # 保存流ID便于跟踪
        'start_time': time.time(),
        'conversation_id': conversation_id,
        'user_id': user_id,
        'content': ''  # 初始化空内容
    }
    stream_data = StreamData(stream_info)
    active_streams[stream_id] = stream_data
    
    # 返回两阶段流式响应
    return StreamingResponse(
        two_phase_response(),
        media_type="text/event-stream",
        headers={
            'Cache-Control': 'no-cache',
            'X-Accel-Buffering': 'no',  # 对Nginx很重要
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',  # 允许跨域，对EventSource很重要
            'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        },
        background=BackgroundTask(on_disconnect)
    ) 